package com.demo.starter.config;

import com.demo.starter.properties.RedissonProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;

/**
 * 说明：Redisson自动配置
 * @author peter
 * @date 2022/2/4 17:46
 */
@Configuration
@EnableConfigurationProperties(RedissonProperties.class)
// 没有引入 redisson 依赖包，RedissonAutoConfiguration 不会生效
@ConditionalOnClass(RedissonClient.class)
// 表示配置文件有 redisson.config-location 属性， 才会启用 RedissonAutoConfiguration 。
@ConditionalOnProperty(prefix = "redisson", name = "config-location")
public class RedissonAutoConfiguration {

    private final ResourceLoader resourceLoader;

    private final RedissonProperties properties;

    // alt + insert 有参构造自动注入
    public RedissonAutoConfiguration(ResourceLoader resourceLoader, RedissonProperties properties) {
        this.resourceLoader = resourceLoader;
        this.properties = properties;
    }

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnMissingBean
    public RedissonClient redissonClient() throws IOException {

        Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());

        Config config = null;
        if (this.properties.getConfigLocation().endsWith(".yaml")) {
            config = Config.fromYAML(resource.getFile());
        } else if (this.properties.getConfigLocation().endsWith(".json")) {
            config = Config.fromJSON(resource.getFile());
        }
        return config != null ? Redisson.create(config) : Redisson.create();
    }
}
